//
//  ZHReachabilityService.m
//  ZHNetworkKit
//
//  Created by green on 2018/3/21.
//

#import "ZHReachabilityService.h"
#import "AFNetworkReachabilityManager.h"
#import <BCFoundation/BCFoundationUtils.h>
#import <BCFileLog/BCFileLog.h>
#import <BCEventBus/BCEventBusKit.h>

@interface ZHReachabilityService()
@property (assign, nonatomic, readwrite) ZHReachabilityStatus     status;//网络状态
@end


@implementation ZHReachabilityService
#pragma mark - system
+ (instancetype)sharedService {
    static ZHReachabilityService *_sharedService = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedService = [[ZHReachabilityService alloc] init];
    });
    
    return _sharedService;
}
+ (instancetype)sharedInstance {
    return [ZHReachabilityService sharedService];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _status = ZHReachabilityStatusUnknown;
    }
    return self;
}

#pragma mark - start
- (void)start
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    @BCWeakify(self);
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        ZHReachabilityStatus newStatus = (ZHReachabilityStatus)status;
        BCLogInfo(@"[http] reach:%ld",newStatus);
        @BCStrongify(self);
        if (self.status != newStatus) {
            //网络状态变更
            ZHReachabilityStatus oldStatus = self.status;
            self.status = newStatus;
            //发布事件
            [BCPubProtocol(ZHReachabilityServiceDelegate) withHandle:^(id<ZHReachabilityServiceDelegate>  _Nonnull target) {
                if([target respondsToSelector:@selector(zhreachabilityService:statusChange:)]){
                    [target zhreachabilityService:self statusChange:oldStatus];
                }
            }];
        }
    }];
}
- (void)stop {
    [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
}

#pragma mark - utils
- (BOOL )isWWAN
{
    return (self.status == ZHReachabilityStatusReachableViaWWAN);
}

- (BOOL )isAvailable
{
    return (self.status == ZHReachabilityStatusReachableViaWWAN || self.status == ZHReachabilityStatusReachableViaWiFi);
}




@end
